package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.graphics.Typeface
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.DataXX
import com.cheyun.netsalev3.databinding.MyContentDialogLayoutBinding
import com.cheyun.netsalev3.repository.WorkSwitchRepository
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.MainActivity
import com.cheyun.netsalev3.widget.MyContentDialog

class WorkSwitchActivityViewModel(var workSwitchRepository: WorkSwitchRepository) : BaseViewModel() {
    //    0 个人 1 管理层 2 展厅
    var listdata = ArrayList<DataXX>()
    var listview = MutableLiveData<List<DataXX>>()
    var uid = MySharedPreferences.getLoginData()?.member?.uid ?: 0
    var workbench = MySharedPreferences.getWorkbench()

    init {
        workSwitchRepository.getHomeList(uid, this::setHomeData)

    }

    /**
     * 请求列表数据回调
     */
    fun setHomeData(list: List<DataXX>) {
        listdata.addAll(list)
        for (item in listdata) {
            item.IsSelect = item.id == workbench
        }
        listview.postValue(listdata)

    }


    var item: DataXX? = null
    var activity: AppCompatActivity? = null
    /**
     * 点击item
     */
    fun onclickItem(view: View, item: DataXX) {
        this.item = item
        var content = view.context
        if (content is AppCompatActivity) {
            this.activity = content
            var pop = MyContentDialog.newInstance("工作台切换", "是否切换为${item.title}？")
            pop.show(content.supportFragmentManager, "")
            pop.callbackInitView = this::initView
            var moth: () -> Unit = {
                workSwitchRepository.setWorkbench(uid, item.id, this::setData)
            }
            pop.onClickOk = moth

        }

    }

    /**
     * 请求回调
     */
    fun setData(workbench: Int) {
        activity?.apply {
            for (i in listdata) {
                i.IsSelect = i.id == item?.id
            }
            MySharedPreferences.setWorkbench(workbench)
            var intent = Intent(this, MainActivity::class.java)
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent)
            MyToast("切换成功")
        }

    }

    /**
     * popview 初始化回调
     */
    fun initView(binding: MyContentDialogLayoutBinding) {
        binding.imageView.visibility = View.VISIBLE
        binding.titleText.typeface = Typeface.DEFAULT_BOLD
    }
}